/** Class Name: OORTeleSalesLEadEmailHandler 
 * Author: Accenture
 * Date: 17-April-2011
 * Requirement/Project Name: OORTelesales
 * Requirement Description: Handles incoming email on Lead
 **/

global class OORTelesalesLeadEmailHandler  implements Messaging.InboundEmailHandler 
{
      /**
       *  Handles the inbound e-mail.
       *
       */
      global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) 
      {
         final Messaging.InboundEmailResult result = new Messaging.InboundEmailresult(); 
         final Pattern emailPattern = Pattern.compile(OORTelesalesTextConstant.LEAD_ID_PATTERN);
         
         String txt =email.subject;
         String leadID = null;
         Integer startIndex = null;
         Integer endIndex = null;
         boolean found = true; 
      
         Matcher emailMatcher = emailPattern.matcher(txt);

         // Searching the Subject  for lead id Pattern 
         if( txt!= null && emailMatcher.find())
         {
             found = false;
             startIndex = emailMatcher.start();
             endIndex = emailMatcher.end();
             leadID =txt.substring(startIndex,endIndex );
           
         }
         else
         {
            // Searching the mail message  for Lead id  Pattern 
             txt = email.plainTextBody;
             emailMatcher = emailPattern.matcher(txt);
             if( txt!= null && emailMatcher.find())
             {
                found = false;
                startIndex = emailMatcher.start();
                endIndex = emailMatcher.end();
                leadID  =txt.substring(startIndex,endIndex );
             }              
         }
         
         // Check if pattern is found 
         if(found)
         {
                 System.debug('Lead ID Pattern not found ');
         }
         else
         {
               insertTask(leadID ,email);
         }
                 
         return result;
      }
      
    /**
     * Insert the Task if the Lead ID  match is found.
     *   
     */
     public void insertTask(String leadId , Messaging.InboundEmail email )
     {
        
        final List<Lead>  leadList =[select id, ownerid  from Lead  where id = :leadId.trim() ];                     
        final RecordTypeIDs__c listViewIDObj = RecordTypeIDs__c.getInstance(userinfo.getProfileId());             
        final List <Task> taskList = new List<Task>();
       
        List <Attachment> attachmentList ;
        Task newTask;
        
        // Check if any Lead is present in the List.
        if(leadList.size() > 0 )
        {
            String ownerID = leadList.get(0).ownerid;
            newTask = new Task(
                                   RecordTypeID = listViewIDObj.OOR_Telesales_Task_RecordType__c,
                                   Description = email.plainTextBody ,
                                   Priority = 'Normal',
                                   Subject = email.subject,
                                   ReminderDateTime = System.now(),
                                   whoId = leadList.get(0).id);   
                                      
            // Check the Lead object  owner is queue or  user                  
            if(ownerID.startsWith(OORTelesalesTextConstant.USER_ID_STARTS_WITH))
            {
                newTask.OwnerID = ownerID;                         
            }
            else
            {
                // Lead owner is Queue
                System.debug('Lead Owner is a Queue');  
            }     
            taskList.add(newTask);           
       }
       else
       {
            System.debug('invalid Lead ID' + leadId );
       } 
                        
       try
       {
            if(taskList.size()> 0)
            {
                    insert taskList ;
                    attachmentList = processEmailAttachment(email,taskList);
                    if(attachmentList !=null && attachmentList.size() > 0 )
                    {
                        insert attachmentList;
                    }
            }
       }
       catch(Exception e )
       {
            GeneralConstants.mailAnyExceptionToMe('OORTeleSalesLEadEmailHandler ','insertTask',e);
       } 
   }
   
   /**
    * Process any attchment if peresent in  inbound email.
    *
    */   
    private List<Attachment> processEmailAttachment( Messaging.InboundEmail email, List<Task> taskList)
    {
        List <Attachment> attachmentList = new List<Attachment>();
        List <Task> tempTaskList = [Select id,ownerID  from Task where id = : taskList.get(0).id]; 
   
        if(tempTaskList.size() > 0)
        {
             // Check if we have any text attachment                       
             if (email.textAttachments!= null && email.textAttachments.size() > 0) 
             {
                 for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) 
                 {
                     Attachment attachment = new Attachment();
                     attachment.Name = tAttachment.fileName;
                     attachment.Body = Blob.valueOf(tAttachment.body);
                     attachment.ParentId = tempTaskList.get(0).id;
                     attachment.ownerId = tempTaskList.get(0).ownerid;
                     attachmentList.add(attachment); 
                 }
             }
             // Check if we have any binary attachment .       
             if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) 
             {                  
                   for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) 
                   {
                       Attachment attachment = new Attachment();
                       attachment.ParentId = tempTaskList.get(0).id;
                       attachment.ownerId = tempTaskList.get(0).ownerid;
                       attachment.Name = email.binaryAttachments[i].filename;
                       attachment.Body = email.binaryAttachments[i].body;
                       attachmentList.add(attachment); 
                   }     
              }        
         }
         return attachmentList;
     }                       
}